package at.cookieforensics;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.logging.Level;

import org.apache.commons.logging.LogFactory;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.util.Cookie;
import com.gargoylesoftware.htmlunit.WebClient;

/**
 * a class which manages all HtmlUnit functionality
 * it handles user agent string generation and cookie management
 * 
 * @author Martin Grottenthaler
 *
 */
public class HtmlUnit {

	/**
	 * WebClient for HtmlUnit
	 */
	private WebClient webClient;
	/**
	 * whether use is logged in or not
	 */
	private boolean loggedIn = false;
	
	/**
	 * basic HtmlUnit setup and user agent string setup
	 * @param browser
	 */
	public HtmlUnit(int browser) {		
	    LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
	    java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);
		java.util.logging.Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.OFF);

		/*
		 * Windows XP		(Windows NT 5.1)
		 * Windows Vista	(Windows NT 6.0)
		 * Windows 7		(Windows NT 6.1)
		 * Windows 8		(Windows NT 6.2)
		 * Windows 8.1		(Windows NT 6.3)
		 * 
		 * Mozilla/5.0		Application name and version. For historical reasons, Internet Explorer identifies itself as a Mozilla browser.
		 * 
		 * Trident/7.0		IE11
		 * Trident/6.0		Internet Explorer 10
		 * Trident/5.0		Internet Explorer 9
		 * Trident/4.0		Internet Explorer 8
		 * 
		 * Win64; IA64		System has a 64-bit processor (Intel).
		 * Win64; x64		System has a 64-bit processor (AMD).
		 * WOW64			A 32-bit version of Internet Explorer is running on a 64-bit processor.
		 */
		// TODO further changes?
		String applicationName = "Mozilla";
	    String applicationVersion = "5.0";
	    String userAgentFirefox = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20120101 Firefox/29.0";
	    String userAgentChrome = "Mozilla/5.0 (Windows NT 6.1; WOW64) Chrome/34.0.1847.116";
	    String userAgentIE = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
	    String[] userAgent = {userAgentChrome, userAgentFirefox, userAgentIE};
	    
	    int browserVersionNumeric = 29;
	    
		BrowserVersion bv = new BrowserVersion(applicationName, applicationVersion, userAgent[browser], browserVersionNumeric);
		
		webClient = new WebClient(bv);
		// disables css and js -> makes everything a lot faster
	    webClient.getOptions().setCssEnabled(false);
	    webClient.getOptions().setJavaScriptEnabled(false);
	}
	
	/**
	 * checks cookies by loading webpage with corresponding cookies
	 * then checks if source code indicates logged in or logged out status
	 * 
	 * @param cookieList list of cookies for queried page
	 * @return logged in or not
	 */
	public String checkCookie(ArrayList<Cookie> cookieList) {
		String requestUrl = "http://";
		String domain;
		
		// Chrome saves some cookies with leading '.' -> remove this
		if (cookieList.get(0).getDomain().charAt(0) == '.') {
			domain = cookieList.get(0).getDomain().substring(1);
		} else {
			domain = cookieList.get(0).getDomain();
		}
		
		requestUrl = requestUrl.concat(domain);

		CookieManager cm = new CookieManager();
		webClient.setCookieManager(cm);
		cm.setCookiesEnabled(true);

		for (Cookie cookie : cookieList) {
			cm.addCookie(cookie);
		}
		
		String textsource = null;
		
		try{
		Page currentPage = webClient.getPage(requestUrl);
		WebResponse response = currentPage.getWebResponse();
		textsource = response.getContentAsString();
		
		File tmpFileRequest = new File("request.txt");
		tmpFileRequest.deleteOnExit();
		BufferedWriter bw1 = new BufferedWriter(new FileWriter(tmpFileRequest));
		bw1.write(response.getWebRequest().toString());
		bw1.close();
		
		File tmpFileResponse = new File("response.html");
		tmpFileResponse.deleteOnExit();
		BufferedWriter bw2 = new BufferedWriter(new FileWriter(tmpFileResponse));
		bw2.write(textsource);
		bw2.close();
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		
		CookieSite cs = new CookieSite(textsource, domain);
		loggedIn = cs.isLoggedIn();
		
		return cs.getMessage();
	}

	/**
	 * whether user is logged in or not
	 * @return login status
	 */
	public boolean isLoggedIn() {
		return loggedIn;
	}
}
